<template>
  <!-- 法规 -->

  <div class="dialog">
    <div class="lf">
      <!-- 搜索 -->
      <div class="lawSearch">
        <div class="inputBox">
          <div class="searchSvg">
            <svg-icon icon-class="ss_icon"></svg-icon>
          </div>
          <input
            type="text"
            placeholder="搜索法规"
            v-model="lawSearchValue"
            @keyup.enter="keyUpLawSearchValue(1)"
          />
        </div>
      </div>
      <el-menu
        ref="menuLaw"
        :default-active="selectLawId"
        class="el-menu-vertical-demo"
        background-color="#F6F7FA"
        active-text-color="#E37809"
        @select="handleSelect"
      >
        <!-- <el-submenu
          index="1"
          @mouseover.native="handleMousemove($event, 15, 1)"
          @mouseout.native="handleMousemove($event, 15, 0)"
        >
          <template slot="title">
            <span ref="test">法律</span>
          </template>
          <el-tooltip
            v-for="(item, idx) in toolateData"
            :key="item.id"
            effect="dark"
            offset="-20"
            enterable
            placement="top-start"
            :manual="true"
            :value="item.disabled"
          >
            <div
              slot="content"
              v-html="$options.filters.fixedNumber(item.content, 15)"
            ></div>
            <el-menu-item :index="item.id" :data-id="idx">
              <p>{{ item.content }}</p>
            </el-menu-item>
          </el-tooltip>
        </el-submenu> -->

        <el-submenu
          :index="item.type"
          v-for="(item, idx) in menuData"
          :key="idx"
        >
          <template slot="title">
            <span ref="test">{{ item.name }}</span>
          </template>
          <el-tooltip
            class="tooltip"
            v-for="(t, i) in item.laws"
            :key="i"
            effect="dark"
            offset="-10"
            :content="t.title"
            transition="el-fade-in-linear"
            placement="top-start"
            :enterable="false"
            :disabled="t.title.length > tooltipLength ? false : true"
          >
            <el-menu-item :index="t.id" :data-id="t.id">
              <p>{{ t.title }}</p>

              <!-- 是否选择了发条 -->
              <div
                class="round_hook_icon"
                v-show="
                  menuHookList.includes(t.id)
                    ? (t.isHook = true)
                    : (t.isHook = false)
                "
              >
                <svg-icon icon-class="round_hook_icon"></svg-icon>
              </div>
            </el-menu-item>
          </el-tooltip>
        </el-submenu>

        <!-- ----  -->
      </el-menu>
    </div>
    <div class="rt">
      <div class="rt-title">
        《{{ rowObj.title }}》
        <div class="searchLawContent">
          <div class="searchSvg">
            <svg-icon icon-class="ss_icon"></svg-icon>
          </div>
          <input
            type="text"
            placeholder="支持法规全文搜索"
            v-model="lawSearchContentValue"
            @keyup.enter="keyUpLawSearchValue(2)"
          />
        </div>
      </div>
      <div class="rt-content">
        <el-checkbox-group v-model="checkList">
          <div v-for="item in rowObj.info" :key="item.id" class="">
            <el-checkbox
              :label="item.id"
              @change="handleCheckedCitiesChange(item)"
            >
              <p v-html="item.content.join('</br>')"></p>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <div class="rt-foot">
        <div class="foot-l">
          <span
            >已选 <em>{{ num }}</em> 条法规</span
          >
          <span class="btn" @click="comfirnFn">确定</span>
        </div>
      </div>
    </div>
    <slot></slot>
  </div>
</template>

<script>
import {
  getLawListApi,
  getLawListTitleApi,
  getLawInfoApi,
} from "@/wss/newApi_3-24/doc/law.js";
import { getDocSelectEsIdApi } from "@/wss/newApi_3-24/work/doc.js";

export default {
  props: {
    // 记录要插入法条的id
    addLawid: {
      type: String,
    },
    dialogVisible: {
      type: Boolean,
      default: false,
    },

    // 选择的法条  内容用于显示

    lawArr: {
      type: Array,
    },
  },
  data() {
    return {
      SwitchButton: false,
      lawSearchValue: "", /// 搜索法律的值
      lawSearchContentValue: "", /// 搜索法条内容的值
      docId: "",
      num: 0, // 几条数据
      tooltipLength: 10, //tooltip 组件超过十个数字显示
      toolateData: [], // 导航切换的列表
      menuData: [], // 导航切换的列表 new
      menuHookList: [], // 导航的列表的id  是否勾选svg图显示隐藏

      isShowDialogLaw: false,
      toolateFirst: "",
      // 全部法律的内容
      rowsList: [],
      // 一部法律的内容
      rowObj: {},
      selectLawId: "", // 导航 选择的法条id
      selectLawTitle: "", // 导航 选择的法条 名称

      checkList: [],
      checkList2: [],
    };
  },
  watch: {
    dialogVisible: {
      handler(newVal, oldVal) {
        console.log("dialogVisible", newVal);
        this.openDialogLaw(newVal);
      },
      immediate: true,
    },

    lawSearchContentValue: function (val) {
      if (!val) {
        console.log("没有了", val);

        this.keyUpLawSearchValue(1);
      }
    },
  },
  created() {},
  mounted() {
    this.getLawListTitleApi();
  },

  // 过滤器
  filters: {
    fixedLength: function (soure, start) {
      console.log(soure.length > start ? true : false);
      return soure.length > start ? true : false;
    },
    // 长度超过start 就添加<br />
    fixedNumber: function (soure, start) {
      return soure.slice(0, start) + "<br/>" + soure.slice(start);
      //插入
      //为字符串插入字符 其中soure为原字符串,start为将要插入字符的位置，newStr为要插入的字符
      // function insertStr(soure, start, newStr){
      //    return soure.slice(0, start) + newStr + soure.slice(start);
      // }
    },
  },
  methods: {
    // 回显 查询某部法律内容api
    async getEchoLawInfoApiFn(list) {
      console.log("list", list);
      list.map(async (item) => {
        const result = await getLawInfoApi({ id: item.f_id });
        console.log("回显----查询某部法律内容api", result);
        if (result.code == 200) {
          item.c_list.forEach((c) => {
            let r_findIndex = result.data.info.findIndex((r) => {
              return r.id == c;
            });

            console.log("r_findIndex", r_findIndex);
            this.checkList2.push({
              esId: item.f_id,
              ...result.data.info[r_findIndex],
            });
          });
        }
      });
      console.log("list_this.checkList2", this.checkList2);
    },

    // 查询某部法律内容api
    async getLawInfoApiFn(data) {
      const result = await getLawInfoApi(data);
      console.log("查询某部法律内容api", result);

      if (result.code == 200) {
        this.rowObj = result.data;
        this.selectLawId = result.data.id;
        this.selectLawTitle = result.data.title;
        this.getDocSelectEsIdFn(this.selectLawId);

        if (this.SwitchButton) {
          setTimeout(() => {
            console.log("lawarr长度大于0", this.lawArr);
            if (this.lawArr.length > 0) {
              this.chooseLawEcho(); // 回显
            }
          }, 2000);
          this.SwitchButton = false;
        }
      }
    },

    // 查询法律标题
    async getLawListTitleApi(data) {
      let result = await getLawListTitleApi(data);
      if (result.code == 200) {
        console.log("查询法律标题", result);
        result.data.forEach((item) => {
          if (item.laws.length > 0) {
            item.laws.forEach((t) => {
              t.isHook = false;
            });
          }
        });

        const menuData = JSON.parse(JSON.stringify(result.data));
        this.menuData = menuData;
        if (!menuData[0]?.laws?.[0]?.id) {
          return;
        }
        // this.menuData[0].laws[0].id; // 默认显示第一部的法律详情

        this.getLawInfoApiFn({ id: menuData[0]?.laws?.[0]?.id });
      }
    },

    // 查修docid函数
    async getDocSelectEsIdFn(id) {
      let result = await getDocSelectEsIdApi({ id: id.substring(0, 16) });
      if (result.code == 200) {
        console.log("查修docid函数", result.data);
        this.docId = result.data.id;
      }
    },

    //////////////////// api ///////////////////////////

    // 关闭对话框
    closeFn() {
      this.$emit("update:dialogVisible", false);
      this.checkList2 = [];
      // document.getElementById("app").style.height = "";
      // document.getElementById("app").style.overflow = " ";

      document.body.style.overflow = "visible";
    },
    // 法律搜索
    keyUpLawSearchValue(judge) {
      if (judge == 1) {
        console.log(this.lawSearchValue);
        this.toolateData = [];
        this.getLawListTitleApi({ name: this.lawSearchValue });
      } else if (judge == 2) {
        // 搜索法条内容

        // 重新改
        // this.getLawInfoApiFn()

        let info_arr = this.rowObj.info;
        console.log("info_arr", info_arr);
        let ARR = [];
        info_arr.map((content_item, content_idx) => {
          //
          content_item.content.forEach((item) => {
            ///
            if (item.indexOf(this.lawSearchContentValue) != -1) {
              let yesNo = item.indexOf(this.lawSearchContentValue);
              console.log("yesNo", yesNo, item, content_idx);
              ARR.push(info_arr[content_idx]);
            }
          });
          //
        });
        this.$set(this.rowObj, "info", ARR);
        console.log("contentItem", ARR);
        console.log(this.lawSearchContentValue, this.rowObj);
      }
    },

    // 菜单栏 ：鼠标移动事件
    /*
     *  e
     *  number			文本长度-超过bumber 换行处理
     *  enter 			鼠标移动状态  1进入  0移出
     */

    // handleMousemove(e, number, enter) {
    //   console.log(number, enter);
    //   let innerText = e.target.innerText;
    //   if (innerText.length >= number) {
    //     if (e.target.nodeName.toLowerCase() === "li") {
    //       enter
    //         ? (this.toolateData[e.target.dataset.id].disabled = true)
    //         : (this.toolateData[e.target.dataset.id].disabled = false);
    //     } else if (e.target.nodeName.toLowerCase() === "p") {
    //       enter
    //         ? (this.toolateData[e.target.parentNode.dataset.id].disabled = true)
    //         : (this.toolateData[
    //             e.target.parentNode.dataset.id
    //           ].disabled = false);
    //     }
    //   }
    // },

    // 切换菜单
    async handleSelect(id, keyPath) {
      console.log("-------", id, this.toolateData, keyPath);
      this.selectLawId = id;

      console.log(this.selectLawId, this.selectLawTitle, "切换时候");
      await this.getDocSelectEsIdFn(id);
      this.getLawInfoApiFn({ id: this.selectLawId });

      // this.rowsList.forEach((item) => {
      //   if (id === item.id) {
      //     this.rowObj = item;
      //   }
      // });
    },

    // 多选
    handleCheckedCitiesChange(item) {
      item.esId = this.selectLawId;

      let isEmpty = this.checkList2.findIndex((v) => {
        return item.id == v.id;
      });
      console.log(isEmpty);
      if (isEmpty != -1) {
        this.num -= 1;
        this.checkList2.splice(isEmpty, 1);
        // 勾选显示;
        this.menuHookList.splice(isEmpty, 1);
      } else {
        this.checkList2.push(item);
        this.num += 1;
        // 勾选显示;
        this.menuHookList.push(item.esId);
      }

      console.log(
        "checkList2",
        this.checkList2,
        this.menuHookList,
        this.checkList
      );
    },

    // 确认函数
    comfirnFn() {
      let arr = [];
      let lawListArr = []; // 用于选择后的法条的显示
      this.num = 0;
      // 传递出去前改造成后端需要
      console.log(this.checkList2, this.menuData[0].laws);
      this.checkList2.map((item, index) => {
        console.log("arrr内部", item);

        let isIn = lawListArr.findIndex((v) => v.esId == item.esId);
        console.log(isIn, index);
        if (isIn !== -1) {
          //  存在返回 下标
          lawListArr[isIn].children.push(item);
          lawListArr[isIn].children.sort((t1, t2) => t1.sort - t2.sort); //排序 从小到大
        } else {
          // 拿到title 组装到lawListArr 数组中
          for (let i = 0; i < this.menuData.length; i++) {
            console.log(i);
            let s_item = this.menuData[i].laws.find((v) => v.id == item.esId);
            console.log(s_item, "s_item");
            if (s_item) {
              this.selectLawTitle = s_item.title;

              lawListArr.push({
                esId: item.esId,
                title: this.selectLawTitle,
                children: [item],
              });
            }
          }
        }
        console.log("lawListArr", lawListArr);
      });

      // 传递出去前改造成后端需要
      this.checkList2.forEach((item) => {
        console.log(item, "itemitem");
        arr.push({
          itemId: item.id,
          esId: item.esId,
          docId: this.docId,
        });
      });

      // this.selectLawList = arr;
      this.$emit("chooseLawData", arr, lawListArr);
      this.closeFn();
    },
    // 打开弹窗
    openDialogLaw(val) {
      console.log(val);
      // this.isShowDialogLaw = val;
      this.SwitchButton = val;
    },
    // 关闭弹窗
    closeDialogLaw() {
      console.log("关闭");
      this.$emit("closeDialogLaw", false);
    },

    //  处理已选法条 回显逻辑
    chooseLawEcho() {
      let new_list = []; // 数据给到  checkList2
      let menu_hook_list = []; // // 导航法条是否勾选 menuHookList
      console.log("lawarrr1111", this.checkList2);
      this.lawArr.forEach((item) => {
        this.checkList.push(item.itemId);
        menu_hook_list.push(item.esId);
      });

      this.checkList.map((item) => {
        console.log(item);
        let find_index = new_list.findIndex(
          (t) => item.split("_")[0] == t.f_id
        );
        console.log("find_index", find_index);
        if (find_index == -1) {
          new_list.push({
            f_id: item.split("_")[0],
            c_list: [item],
          });
        } else {
          new_list[find_index].c_list.push(item);
        }
        // a=[{
        //   f_id:'122',
        //   c_list:['1','2','3']
        // }]
        console.log("new_list 这个是回显的数据", new_list);
      });
      this.menuHookList = [...new Set(menu_hook_list)]; // 导航法条是否勾选

      this.num = this.checkList.length; // 已经选择的法条数量

      console.log("menuHookList", this.menuHookList);
      console.log("lawArr", this.lawArr);
      console.log("checkList2", this.checkList2);
      console.log("selectLawId", this.selectLawId);

      console.log("checkList", this.checkList);

      this.getEchoLawInfoApiFn(new_list);
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  display: flex;
  ::v-deep .el-dialog--center {
    top: 15%;
    height: 70%;
    margin-top: 0 !important;
    .el-dialog__header {
      border-bottom: 0.1rem solid #e3e3e3;
    }
    .el-dialog__body {
      display: flex;
      padding: 0;
      height: 86%;
      background: #fff;
    }
  }

  .lf {
    width: 240px;
    height: 100%;
    overflow: hidden;
    background: #f6f7fa;
    .lawSearch {
      position: relative;
      height: 77px;
      .inputBox {
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        bottom: 0;
        transform: translateY(-50%);
        margin: auto;
        width: 80%;
        height: 34px;
        line-height: 34px;

        border: 0.1rem solid #e3e3e3;
        .searchSvg {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          left: 6px;
          font-size: 10px;
          color: #ccc;
        }
        input {
          display: block;
          padding-left: 30px;
          width: 100%;
          height: 100%;
          font-size: 14px;
          color: #333;
          &::placeholder {
            color: #ccc;
          }
        }
      }
    }
    .el-menu-vertical-demo {
      height: calc(100% - 77px);
      overflow: scroll;
      .el-submenu {
        .el-submenu__title {
          span {
            font-size: 16px;
            font-weight: 600;
            color: #333;
          }
        }
        .el-menu-item {
          position: relative;
          min-width: 0 !important;
          padding: 0 20px !important;
          font-size: 14px;
          color: #666;
          &:hover {
            background: #ffecd6 !important;
          }
          p {
            margin-bottom: 0;
            overflow: hidden;
          }
          .round_hook_icon {
            position: absolute;
            top: 0;
            right: 22px;
            font-size: 8px;
            color: #e37809;
          }
        }
        .el-menu-item.is-active {
          background: #ffecd6 !important;
        }
      }

      //菜单关闭
      ::v-deep .el-submenu > .el-submenu__title .el-submenu__icon-arrow {
        -webkit-transform: rotateZ(-90deg);
        -ms-transform: rotate(-90deg);
        transform: rotateZ(-90deg);
      }
      //菜单展开
      ::v-deep
        .el-submenu.is-opened
        > .el-submenu__title
        .el-submenu__icon-arrow {
        -webkit-transform: rotateZ(0deg);
        -ms-transform: rotate(0deg);
        transform: rotateZ(0deg);
      }
    }

    .tooltip {
      -webkit-transition: none;
      transition: none;
    }
  }
  .rt {
    width: calc(100% - 240px);
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    padding: 0 20px;
    .rt-title {
      flex: 0 0 auto;

      position: relative;
      height: 76px;
      line-height: 76px;
      // 16px == 1.6rem
      font-size: 16px;

      color: #e37809;
      border-bottom: 0.1rem solid #e3e3e3;
      .searchLawContent {
        position: absolute;
        top: 50%;
        right: 0;
        transform: translateY(-50%);

        width: 200px;
        height: 34px;
        line-height: 34px;
        border: 0.1rem solid #e3e3e3;

        .searchSvg {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          left: 6px;
          font-size: 10px;
          color: #ccc;
        }
        input {
          display: block;
          padding-left: 30px;
          width: 100%;
          height: 100%;
          font-size: 14px;
          color: #333;
          &::placeholder {
            color: #ccc;
          }
        }
      }
    }
    .rt-content {
      // flex: 1;
      height: 100%;
      overflow: scroll;

      .el-checkbox-group > div {
        margin-top: 20px;
        margin-bottom: 20px;

        .is-checked {
          background: #e1ebff;
        }
      }
      ::v-deep .el-checkbox {
        position: relative;
        padding: 10px 0;

        font-family: "Microsoft YaHei";
        font-weight: 400;
        width: 100%;

        .el-checkbox__input {
          position: absolute;
          top: 12px;
          .el-checkbox__inner {
            border-radius: 50%;
            width: 16px;
            height: 16px;
          }
          .el-checkbox__inner::after {
            height: 8px;
            left: 5px;
          }
        }
        .el-checkbox__label {
          padding-left: 26px;
          white-space: normal;
        }
      }
      ::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
        color: #527fd0;
      }
      // ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner,
      // .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      //   background-color: #e1ebff;
      //   border-color: #e1ebff;
      // }
    }

    // 底部确定按钮
    .rt-foot {
      flex: 0 0 auto;
      height: 80px;
      line-height: 80px;
      border-top: 0.1rem solid #e3e3e3;
      .foot-l {
        float: right;
        span {
          font-size: 14px;
          color: #333;
          em {
            color: #e37809;
          }
        }
        .btn {
          margin-left: 10px;
          padding: 13px 50px;
          color: #fff;
          background: #e37809;
        }
      }
    }
  }

  .active {
    background: #e1ebff;
  }
}

// .el-tooltip__popper {
//   background: pink;
//   .popper__arrow {
//     left: 2rem !important;
//   }
// }
</style>